package com.xzg.erp.system.web;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzg.erp.common.BusinessException;
import com.xzg.erp.common.Constants;
import com.xzg.erp.common.valid.SelectValid;
import com.xzg.erp.common.valid.UpdateValid;
import com.xzg.erp.system.entity.SysUser;
import com.xzg.erp.system.entity.dto.UserPageDto;
import com.xzg.erp.system.entity.dto.UserQueryDto;
import com.xzg.erp.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2025-02-04
 */
@RestController
@RequestMapping("/sysUser")
@Validated
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/register")
    public ResponseEntity register(@Validated(UpdateValid.class) @RequestBody SysUser sysUser) {
        if (!sysUserService.saveUser(sysUser)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, Constants.FAIL_REGISTER);
        }
        sysUser.setPassword(Constants.BLANK);
        return ResponseEntity.ok(sysUser);
    }

    @PostMapping("/login")
    public ResponseEntity login(@Validated(SelectValid.class) @RequestBody SysUser sysUser) {
        SysUser user = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, sysUser.getUsername()));
        if (Objects.isNull(user)) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED, Constants.USER_NOT_EXIT);
        }
        if (!SaSecureUtil.md5(sysUser.getPassword()).equals(user.getPassword())) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED, Constants.PASSWORD_ERROR);
        }
        user.setPassword(null);
        StpUtil.login(user.getId(), SaLoginConfig.setExtraData(objectMapper.convertValue(user, Map.class)));
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ResponseEntity.ok(tokenInfo);
    }

    @PostMapping("/logout")
    public ResponseEntity logout(@RequestHeader("xzgtoken") String token) {
        StpUtil.logoutByTokenValue(token);
        return ResponseEntity.ok(Constants.SUCCESS);
    }

    @PostMapping("/page")
    public ResponseEntity page(@RequestBody UserQueryDto dto) {
        Page<SysUser> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Page<SysUser> page1 = sysUserService.page(page, Wrappers.<SysUser>lambdaQuery()
                .like(StrUtil.isNotBlank(dto.getUsername()), SysUser::getUsername, dto.getUsername())
                .like(StrUtil.isNotBlank(dto.getRealName()), SysUser::getRealName, dto.getRealName())
                .eq(SysUser::getDeleted, Constants.UN_DELETED)
                .orderByDesc(SysUser::getUpdatedAt));
        IPage<UserPageDto> convert = page1.convert(user -> objectMapper.convertValue(user, UserPageDto.class));
        return ResponseEntity.ok(convert);
    }

}
